package com.feige.utils.file.impl;


import com.feige.utils.file.FsUtils;
import com.feige.utils.file.pojo.FSInfo;
import com.feige.utils.file.FileUdService;
import com.feige.utils.file.pojo.LocalStorageProperties;
import com.feige.utils.file.pojo.UploadInfo;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author feige<br />
 * @ClassName: LocalFileStoreImpl <br/>
 * @Description: <br/>
 * @date: 2021/9/24 17:55<br/>
 */
public class LocalFileUdServiceImpl implements FileUdService {

    Logger logger = LoggerFactory.getLogger(LocalFileUdServiceImpl.class);

    private final LocalStorageProperties localStorageProperties;

    public LocalFileUdServiceImpl(LocalStorageProperties localStorageProperties) {
        this.localStorageProperties = localStorageProperties;
    }

    @Override
    public FSInfo upload(UploadInfo uploadInfo) {
        String group = "local/" + uploadInfo.getFileType() + (uploadInfo.isEnableDatePath() ? "/" + FsUtils.joinFileName() : "");
        try {
            FileUtils.copyInputStreamToFile(uploadInfo.getInputStream(),new File(getPath() + group + "/" + uploadInfo.getFullFileName()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        FSInfo fsInfo = new FSInfo();
        fsInfo.setPath(uploadInfo.getFileName());
        fsInfo.setGroup(group);
        fsInfo.setStorageType(getType());
        fsInfo.setOriginalFilename(uploadInfo.getOriginalFilename());
        logger.info("{}文件上传成功",uploadInfo.getFileName());
        return fsInfo;
    }

    @Override
    public InputStream getFileInputStream(String objectName) {
        String path = getPath() + objectName;
        try {
            return new ByteArrayInputStream(FileUtils.readFileToByteArray(new File(path)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("下载文件出错");
    }

    @Override
    public String getType() {
        return FsUtils.LOCAL;
    }

    private String getPath(){
        File file = new File("");
        String path = localStorageProperties.getPath();
        if (!path.isEmpty()){
            if (path.charAt(path.length() - 1) != '/'){
                path = path + "/";
            }
        }else {
            path = file.getAbsolutePath();
        }
        return path;
    }
}
